package com.kevin.controller.admin;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.shiro.cache.Cache;
import org.apache.shiro.cache.CacheManager;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.servlet.ModelAndView;

import com.kevin.core.easyui.EasyUI;
import com.kevin.core.easyui.Menu;
import com.kevin.core.util.SecurityUtil;
import com.kevin.entity.Staff;
import com.kevin.service.admin.MenuService;
import com.kevin.service.admin.RoleResService;
import com.kevin.service.admin.StaffService;

@Controller
@RequestMapping("/admin")
public class IndexController{
	
	private final String CACHE_KEY_PREFIX="com.kevin.controller.admin.IndexController:";

    @Autowired
    MenuService menuService;
    
    @Autowired
    StaffService staffService;
    
    @Autowired
    RoleResService roleResService;
    
    @Autowired
    CacheManager adminShiroCacheManager;

    @RequestMapping("/")
    public ModelAndView index(HttpServletRequest request, HttpServletResponse response) {
    	Integer staffId=SecurityUtil.getCurrentStaffId();
        Cache<String, Map<String, Object>> cache = adminShiroCacheManager.getCache("adminShiroCache");
        String key=CACHE_KEY_PREFIX+staffId;
        Map<String, Object> model = cache.get(key);
        if(model==null){
        	 model=getModel(request);
        	 cache.put(key, model);
        }
        return new ModelAndView("admin/index",model);
    }

	private Map<String, Object> getModel(HttpServletRequest request) {
		Integer staffId=SecurityUtil.getCurrentStaffId();
        String contentPath=request.getContextPath();
        Staff staff=staffService.findOne(staffId);
        List<Menu> srcList=menuService.findAll();
        List<Menu> menuList=menuService.findAllByStaffId(Integer.valueOf(staffId));
        String menu=EasyUI.getEasyUIMenu(srcList,menuList,contentPath);
        Map<String, Object> model = new HashMap<String, Object>();
        model.put("menu",menu);
        model.put("staff",staff);
		return model;
	}
}
